package com.mowh.multithreading.two.phase.termination.barrier;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author mowh1gd
 * @create 2023/11/27 15:46
 */
public class Main {
    private static final int THREADS = 3;
    public static void main(String[] args) {
        System.out.println("BEGIN");
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Runnable barrierAction = new Runnable() {
            @Override
            public void run() {
                System.out.println("Barrier Action!");
            }
        };
        CyclicBarrier phaseBarrier = new CyclicBarrier(THREADS, barrierAction);
        CountDownLatch doneLatch = new CountDownLatch(THREADS);
        try {
            for (int t = 0; t < THREADS; t++) {
                executorService.execute(new MyTask(phaseBarrier, doneLatch, t));//执行3个任务
            }
            System.out.println("AWAIT");
            doneLatch.await();//等3个线程都执行完成
        } catch (InterruptedException e) {
        } finally {
            executorService.shutdown();
            System.out.println("END");
        }
    }
}
